package com.assistant.lock;

import java.util.concurrent.TimeUnit;

import com.assistant.lock.RedisLock;
import com.assistant.lock.annotation.Lock;
import com.assistant.lock.handler.LockRejectHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public enum RejectedPolicy {
    ABORT {
        public LockRejectHandler getHandler() {
            return new LockRejectHandler() {
                public void handle(com.assistant.lock.RedisLock lock) {
                    RejectedPolicy.LOGGER.warn("@Lock加锁失败，中止任务:{}", lock.getName());
                    throw new RuntimeException(lock.getMsg());
                }
            };
        }
    },
    WAIT {
        public LockRejectHandler getHandler() {
            return new LockRejectHandler() {
                public void handle(com.assistant.lock.RedisLock lock) {
                    RejectedPolicy.LOGGER.warn("@Lock加锁中，等待任务:{}", lock.getName());

                    for(int count = 0; count < 70; ++count) {
                        try {
                            TimeUnit.MILLISECONDS.sleep(30L);
                            boolean isLocked = lock.tryLock();
                            if (isLocked) {
                                RejectedPolicy.LOGGER.info("@Lock加锁成功:{}", lock.getName());
                                RedisLock.LOCK_THREAD_LOCAL.set(lock);
                                return;
                            }
                        } catch (InterruptedException var4) {
                            RejectedPolicy.LOGGER.error("InterruptedException error", var4);
                        }
                    }

                }
            };
        }
    };

    private static final Logger LOGGER = LoggerFactory.getLogger(Lock.class);

    private RejectedPolicy() {
    }

    public abstract LockRejectHandler getHandler();
}
